package com.pureut.quality.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.production.api.FeignProductionService;
import com.pureut.production.api.domain.vo.EditQualityOrderVo;
import com.pureut.quality.domain.PublicGoods;
import com.pureut.quality.domain.QualitySchemeConfiguration;
import com.pureut.quality.domain.QualitySchemeConfigurationDetail;
import com.pureut.quality.domain.dto.QualitySchemeConfigurationDetailDto;
import com.pureut.quality.domain.dto.QualitySchemeConfigurationDto;
import com.pureut.quality.domain.vo.InspectionVo;
import com.pureut.quality.domain.vo.QualitySchemeConfigurationVo;
import com.pureut.quality.mapper.PublicGoodsMapper;
import com.pureut.quality.mapper.QualitySchemeConfigurationDetailMapper;
import com.pureut.quality.mapper.QualitySchemeConfigurationMapper;
import com.pureut.quality.service.QualitySchemeConfigurationDetailService;
import com.pureut.quality.service.QualitySchemeConfigurationService;
import com.pureut.system.api.domain.SysDictData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/***
 * 检验方案配置表实现层
 * Author:C
 * Date:2023/02/02 17:08
 * @DESC
 */
@Service
public class QualitySchemeConfigurationServiceImpl extends ServiceImpl<QualitySchemeConfigurationMapper, QualitySchemeConfiguration> implements QualitySchemeConfigurationService {

    @Resource
    QualitySchemeConfigurationMapper qualitySchemeConfigurationMapper;

    @Resource
    QualitySchemeConfigurationDetailService qualitySchemeConfigurationDetailService;

    @Resource
    QualitySchemeConfigurationDetailMapper qualitySchemeConfigurationDetailMapper;

    @Resource
    FeignProductionService feignProductionService;

    @Resource
    PublicGoodsMapper publicGoodsMapper;

    /**
     * 检验方案配置列表
     *
     * @param qualitySchemeConfigurationVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<QualitySchemeConfigurationDto> getSchemeConfigurationList(QualitySchemeConfigurationVo qualitySchemeConfigurationVo) {
        //检验方案配置列表
        List<QualitySchemeConfigurationDto> schemeConfigurationList = qualitySchemeConfigurationMapper.getSchemeConfigurationList(qualitySchemeConfigurationVo);

        //检测阶别
        List<SysDictData> rankArray = DictUtils.getDictCache("item_rank");
        Map<String, String> rankMap = rankArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //方案类型
        List<SysDictData> schemeTypeArray = DictUtils.getDictCache("quality_scheme_type");
        Map<String, String> schemeTypeMap = schemeTypeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //类别
        List<SysDictData> categoryArray = DictUtils.getDictCache("quality_category");
        Map<String, String> categoryMap = categoryArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //生产阶别
        List<SysDictData> productionLevelArray = DictUtils.getDictCache("quality_production_level");
        Map<String, String> productionLevelMap = productionLevelArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //抽样方式
        List<SysDictData> samplingMethodArray = DictUtils.getDictCache("quality_sampling_method");
        Map<String, String> samplingMethodMap = samplingMethodArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (QualitySchemeConfigurationDto entity : schemeConfigurationList) {
            //检测阶别
            entity.setItemRankDict(rankMap.get(entity.getItemRank()));
            //方案类型
            entity.setSchemeTypeDict(schemeTypeMap.get(entity.getSchemeType()));
//            if ("2".equals(entity.getSchemeType())) {
            //类别
            entity.setCategoryDict(categoryMap.get(entity.getTypeCategory()));
//            } else {
//                //类别
//                entity.setCategoryDict(categoryMap.get(entity.getTypeCategory()));
//            }

            //生产阶别
            entity.setProductionLevelDict(productionLevelMap.get(entity.getProductionLevel()));
            //抽样方式
            entity.setSamplingMethodDict(samplingMethodMap.get(entity.getSamplingMethod()));

        }

        return schemeConfigurationList;
    }

    /**
     * 检验方案配置新增
     *
     * @param qualitySchemeConfigurationVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(QualitySchemeConfigurationVo qualitySchemeConfigurationVo) throws Exception {
        //判断是否选择了检验项目
        List<InspectionVo> inspectionItem = qualitySchemeConfigurationVo.getInspectionItem();
        if (inspectionItem.size() < 1) {
            throw new GlobalException("至少选择一条检验项目");
        }
        //校验同一检测阶别、类别、生产阶别、物料类别/物料编码 下，只允许存在一条方案配置
        Long result1 = null;
        Long result2 = null;
        if (qualitySchemeConfigurationVo.getSchemeType() == 1) {
            result1 = qualitySchemeConfigurationMapper.getConfigurationCategory(qualitySchemeConfigurationVo);
        }
        if (qualitySchemeConfigurationVo.getSchemeType() == 2) {
            result2 = qualitySchemeConfigurationMapper.getConfigurationMaterial(qualitySchemeConfigurationVo);
        }
        if (result1 != null) {
            throw new GlobalException("同一检测阶别、类别、生产阶别、物料类别下，只允许存在一条方案配置");
        }
        if (result2 != null) {
            throw new GlobalException("同一检测阶别、类别、生产阶别、物料编码下，只允许存在一条方案配置");
        }
        PublicGoods publicGoods = null;
        if (qualitySchemeConfigurationVo.getSchemeType() == 2) {
            publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, qualitySchemeConfigurationVo.getMaterialCode()));
        }

        QualitySchemeConfiguration qualitySchemeConfiguration = new QualitySchemeConfiguration();
        qualitySchemeConfiguration.setItemRank(qualitySchemeConfigurationVo.getItemRank());
        if (publicGoods != null) {
            qualitySchemeConfiguration.setCategory(publicGoods.getMaterialCategory())
                    .setMaterialCategory(publicGoods.getMaterialType());
        } else {
            qualitySchemeConfiguration.setCategory(qualitySchemeConfigurationVo.getCategory())
                    .setMaterialCategory(qualitySchemeConfigurationVo.getMaterialCategory());
        }

        qualitySchemeConfiguration.setProductionLevel(qualitySchemeConfigurationVo.getProductionLevel())
                .setMaterialCode(qualitySchemeConfigurationVo.getMaterialCode())
                .setSamplingMethod(qualitySchemeConfigurationVo.getSamplingMethod())
                .setSamplingNum(qualitySchemeConfigurationVo.getSamplingNum())
                .setSchemeType(qualitySchemeConfigurationVo.getSchemeType())
                .setCreateTime(new Date())
                .setDeptId(SecurityUtils.getDeptId());
        save(qualitySchemeConfiguration);

        //存储明细状态
        List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetailList = new ArrayList<>();

        for (InspectionVo entity : inspectionItem) {
            QualitySchemeConfigurationDetail qualitySchemeConfigurationDetail = new QualitySchemeConfigurationDetail();
            qualitySchemeConfigurationDetail.setSchemeId(qualitySchemeConfiguration.getId());
            qualitySchemeConfigurationDetail.setLowerLimitValue(entity.getItemLowerLimit());
            qualitySchemeConfigurationDetail.setUpperLimitValue(entity.getItemUpperLimit());
            qualitySchemeConfigurationDetail.setInspectionId(entity.getId());
            qualitySchemeConfigurationDetail.setCreateTime(new Date());
            qualitySchemeConfigurationDetail.setDeptId(SecurityUtils.getDeptId());
            qualitySchemeConfigurationDetail.setProjectCode(entity.getItemCode());
            qualitySchemeConfigurationDetailList.add(qualitySchemeConfigurationDetail);
        }
        EditQualityOrderVo editQualityOrderVo = new EditQualityOrderVo();
        editQualityOrderVo.setMaterialCode(qualitySchemeConfiguration.getMaterialCode());
        editQualityOrderVo.setMaterialType(String.valueOf(qualitySchemeConfigurationVo.getMaterialCategory()));
        feignProductionService.editQualityOrder(editQualityOrderVo);
        return qualitySchemeConfigurationDetailService.saveBatch(qualitySchemeConfigurationDetailList);
    }

    /**
     * 检验方案查看
     *
     * @param id
     * @return
     */
    @Override
    public QualitySchemeConfigurationDto view(long id) {

        //检测阶别
        List<SysDictData> rankArray = DictUtils.getDictCache("item_rank");
        Map<String, String> rankMap = rankArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //方案类型
        List<SysDictData> schemeTypeArray = DictUtils.getDictCache("quality_scheme_type");
        Map<String, String> schemeTypeMap = schemeTypeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //类别
        List<SysDictData> categoryArray = DictUtils.getDictCache("quality_category");
        Map<String, String> categoryMap = categoryArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //生产阶别

        List<SysDictData> productionLevelArray = DictUtils.getDictCache("quality_production_level");
        Map<String, String> productionLevelMap = productionLevelArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //抽样方式
        List<SysDictData> samplingMethodArray = DictUtils.getDictCache("quality_sampling_method");
        Map<String, String> samplingMethodMap = samplingMethodArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //获取检验方案配置
        QualitySchemeConfigurationDto viewById = qualitySchemeConfigurationMapper.getViewById(id);

        //检测阶别
        viewById.setItemRankDict(rankMap.get(viewById.getItemRank()));
        //方案类型
        viewById.setSchemeTypeDict(schemeTypeMap.get(viewById.getSchemeType()));
        //类别
        viewById.setCategoryDict(categoryMap.get(viewById.getCategory()));
        //生产阶别
        viewById.setProductionLevelDict(productionLevelMap.get(viewById.getProductionLevel()));
        //抽样方式
        viewById.setSamplingMethodDict(samplingMethodMap.get(viewById.getSamplingMethod()));

        //获取检验方案配置明细列表
        List<QualitySchemeConfigurationDetailDto> schemeConfigurationDetailList = qualitySchemeConfigurationDetailService.getSchemeConfigurationDetailList(id);

        //单位
        List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //管控方式
        List<SysDictData> controlModeArray = DictUtils.getDictCache("quality_item_control_mode");
        Map<String, String> controlModeMap = controlModeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (QualitySchemeConfigurationDetailDto entity : schemeConfigurationDetailList) {
            //管控方式
            entity.setItemControlModeDict(controlModeMap.get(entity.getItemControlMode()));
            //单位
            entity.setItemUnitDict(unitMap.get(entity.getItemUnit()));
        }
        viewById.setDetailList(schemeConfigurationDetailList);

        return viewById;
    }

    /**
     * 修改检验方案配置
     *
     * @param qualitySchemeConfigurationVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateConfiguration(QualitySchemeConfigurationVo qualitySchemeConfigurationVo) {

        //获取之前的检验方案配置
        QualitySchemeConfiguration qualitySchemeConfiguration = getById(qualitySchemeConfigurationVo.getId());

//        //校验同一检测阶别、类别、生产阶别、物料类别/物料编码 下，应 只允许存在一条方案配置
//        List<QualitySchemeConfiguration> qualitySchemeConfigurationList = null;
//        if(qualitySchemeConfigurationVo.getSchemeType() == 1){
//            qualitySchemeConfigurationList = qualitySchemeConfigurationMapper.selectList(new QueryWrapper<QualitySchemeConfiguration>().lambda()
//                    .eq(QualitySchemeConfiguration::getItemRank, qualitySchemeConfigurationVo.getItemRank())
//                    .eq(QualitySchemeConfiguration::getCategory, qualitySchemeConfigurationVo.getCategory())
//                    .eq(QualitySchemeConfiguration::getProductionLevel, qualitySchemeConfigurationVo.getProductionLevel())
//                    .eq(QualitySchemeConfiguration::getMaterialCategory, qualitySchemeConfigurationVo.getMaterialCategory())
//                    .eq(QualitySchemeConfiguration::getSchemeType, 1));
//        }
//
//        if(qualitySchemeConfigurationVo.getSchemeType() == 2){
//            qualitySchemeConfigurationList = qualitySchemeConfigurationMapper.selectList(new QueryWrapper<QualitySchemeConfiguration>().lambda()
//                    .eq(QualitySchemeConfiguration::getItemRank, qualitySchemeConfigurationVo.getItemRank())
//                    .eq(QualitySchemeConfiguration::getCategory, qualitySchemeConfigurationVo.getCategory())
//                    .eq(QualitySchemeConfiguration::getProductionLevel, qualitySchemeConfigurationVo.getProductionLevel())
//                    .eq(QualitySchemeConfiguration::getMaterialCode, qualitySchemeConfigurationVo.getMaterialCode())
//                    .eq(QualitySchemeConfiguration::getSchemeType, 2));
//        }
//
//        if (qualitySchemeConfigurationList.size() > 1) {
//            throw new GlobalException("同一检测阶别、类别、生产阶别、物料类别/物料编码下，只允许存在一条方案配置");
//        }
        //删除之前的数据
        boolean b = removeById(qualitySchemeConfiguration);
        QualitySchemeConfiguration qualitySchemeConfiguration3 = new QualitySchemeConfiguration();
        if(b){
            qualitySchemeConfiguration3.setItemRank(qualitySchemeConfigurationVo.getItemRank())
                    .setCategory(qualitySchemeConfigurationVo.getCategory())
                    .setProductionLevel(qualitySchemeConfigurationVo.getProductionLevel())
                    .setMaterialCategory(qualitySchemeConfigurationVo.getMaterialCategory())
                    .setMaterialCode(qualitySchemeConfigurationVo.getMaterialCode())
                    .setSamplingMethod(qualitySchemeConfigurationVo.getSamplingMethod())
                    .setSamplingNum(qualitySchemeConfigurationVo.getSamplingNum())
                    .setSchemeType(qualitySchemeConfigurationVo.getSchemeType())
                    .setCreateTime(new Date())
                    .setDeptId(SecurityUtils.getDeptId());
            save(qualitySchemeConfiguration3);
        }


        //删除掉之前的明细
        List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetailList = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, qualitySchemeConfigurationVo.getId()));

        int i = qualitySchemeConfigurationDetailMapper.deleteBatchIds(qualitySchemeConfigurationDetailList);
        if (i > 0) {
            //存储明细状态
            List<QualitySchemeConfigurationDetail> details = new ArrayList<>();

            //获取传过来的列表
            List<InspectionVo> inspectionItem = qualitySchemeConfigurationVo.getInspectionItem();

            for (InspectionVo entity : inspectionItem) {
                QualitySchemeConfigurationDetail qualitySchemeConfigurationDetail = new QualitySchemeConfigurationDetail();
                qualitySchemeConfigurationDetail.setSchemeId(qualitySchemeConfiguration3.getId());
                qualitySchemeConfigurationDetail.setLowerLimitValue(entity.getItemLowerLimit());
                qualitySchemeConfigurationDetail.setUpperLimitValue(entity.getItemUpperLimit());
                qualitySchemeConfigurationDetail.setInspectionId(entity.getInspectionId());
                qualitySchemeConfigurationDetail.setProjectCode(entity.getItemCode());
                qualitySchemeConfigurationDetail.setCreateTime(new Date());
                qualitySchemeConfigurationDetail.setDeptId(SecurityUtils.getDeptId());
                details.add(qualitySchemeConfigurationDetail);
            }
            return qualitySchemeConfigurationDetailService.saveBatch(details);
        }
        return false;
    }

    /**
     * 删除
     *
     * @param idStr
     * @return
     */
    @Override
    public boolean delete(String idStr) {

        List<String> ids = Arrays.asList(idStr.split(","));
        if (ids.size() < 1) {
            throw new GlobalException("至少选择一条数据");
        }
        //根据id获取检验方案配置数据
        List<QualitySchemeConfiguration> qualitySchemeConfigurationList = qualitySchemeConfigurationMapper.selectList(new QueryWrapper<QualitySchemeConfiguration>().lambda().in(QualitySchemeConfiguration::getId, ids));

        //查询该数据下的明细
        List<QualitySchemeConfigurationDetail> detailList = new ArrayList<>();

        for (QualitySchemeConfiguration entity : qualitySchemeConfigurationList) {
            List<QualitySchemeConfigurationDetail> details = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, entity.getId()));
            detailList.addAll(details);
        }
        //删除明细数据
        qualitySchemeConfigurationDetailMapper.deleteBatchIds(detailList);

        //删除检验方案配置数据
        return qualitySchemeConfigurationMapper.deleteBatchIds(qualitySchemeConfigurationList) > 0;
    }

    /**
     * 检验是否配置方案
     *
     * @param qualitySchemeConfigurationVo
     * @return
     */
    @Override
    public boolean check(QualitySchemeConfigurationVo qualitySchemeConfigurationVo) {
        //根据阶别、类别、方案类型、物料编码查询检验项目
        Long configurationListByCode = qualitySchemeConfigurationMapper.getConfigurationListByCode(qualitySchemeConfigurationVo);
        //根据阶别、类别、方案类型、物料类别查询检验项目
        Long configurationListByCategory = qualitySchemeConfigurationMapper.getConfigurationListByCategory(qualitySchemeConfigurationVo);
        return configurationListByCode != null || configurationListByCategory != null;
    }
}
